package com.itheima.controller;

import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/validatecode")
public class Validatecode {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //POST /validatecode/send4Order
    //发送验证码给用户
    @PostMapping("/send4Order")
    public void send4Order(String telephone) {
        log.info("发送验证码给用户：{}", telephone);
        // 发送验证码短信
        //生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);

           // SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE, telephone, code);
            log.info("验证码为：{}", code);

        try {
            //将code保存至redis中 有效期5分钟 键为手机号 值为验证码
            redisTemplate.opsForValue().set(telephone, code, 5, java.util.concurrent.TimeUnit.MINUTES);
            log.info("验证码保存至redis中：{}", code);
        } catch (Exception e) {
            log.error("保存验证码失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
